package com.os.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;

/**
 * @author zhaozhikai
 * @date 2023/12/24 12:24
 */
public class IoUtilPlus {
    private static MessageDigest digest = SecureUtil.createMessageDigest(DigestAlgorithm.SHA256.getValue());
    public static int bufferSize = 8192;
    /**
     * io传输的同时计算hash
     *
     * @param source
     * @param target
     * @return
     * @throws IOException
     */
    public static String copyWithHash(InputStream source, OutputStream target) throws IOException {
        Assert.notNull(source, "InputStream is null !", new Object[0]);
        Assert.notNull(target, "OutputStream is null !", new Object[0]);
        byte[] buffer = new byte[bufferSize];
        int read;
        while(( read = source.read(buffer, 0, bufferSize)) > -1) {
            target.write(buffer, 0, read);
            digest.update(buffer, 0, read);
        }
        String hash = HexUtil.encodeHexStr(digest.digest());
        return hash;
    }
}
